/*

https://www.google.com/calendar/b/0/render?gadgeturl=http://gaeinjail.googlecode.com/svn/www/gadgets/googlecalendar/contactsearch.xml?ts=1

*/
var tabs = null;
var calendar = null;
var contacts = null;
var calendarEntries = null;
var groupEntries = null;
var contactEntries = null;

/*
	duration = 135
	return = {hour: 2, minute: 15, second: 0}
*/

var cancelreasons = ['Justified','Not Justified','Professional'];
//var durations = [15,30,45,60,75,90,10,120,135,150,165,180];
var durations = [30,45,60,75,90,10,120];

function getAsTime(duration)
{
	var ref = {
		"15"  : {hour: 0 , minute: 15, second: 0},
		"30"  : {hour: 0 , minute: 30, second: 0},
		"45"  : {hour: 0 , minute: 45, second: 0},
		"60"  : {hour: 1 , minute:  0, second: 0},
		"75"  : {hour: 1 , minute: 15, second: 0},
		"90"  : {hour: 1 , minute: 30, second: 0},
		"105" : {hour: 1 , minute: 45, second: 0},
		"120" : {hour: 2 , minute:  0, second: 0},
		"135" : {hour: 2 , minute: 15, second: 0},
		"150" : {hour: 2 , minute: 30, second: 0},
		"165" : {hour: 2 , minute: 45, second: 0},
		"180" : {hour: 3 , minute:  0, second: 0},
	};
	
	if (duration in ref)
		return ref[duration];
	else
		return ref[45];
};
	
function getPhoneType(info){
	var types =	{
		"http://schemas.google.com/g/2005#assistant":		"assistant", 		
		"http://schemas.google.com/g/2005#callback":        "callback", 		
		"http://schemas.google.com/g/2005#car":             "car", 			
		"http://schemas.google.com/g/2005#company_main":    "company_main", 	
		"http://schemas.google.com/g/2005#fax":             "fax",			
		"http://schemas.google.com/g/2005#home":            "home", 			
		"http://schemas.google.com/g/2005#home_fax":        "home_fax", 		
		"http://schemas.google.com/g/2005#isdn":            "isdn", 			
		"http://schemas.google.com/g/2005#main":            "main", 			
		"http://schemas.google.com/g/2005#mobile":          "mobile", 		
		"http://schemas.google.com/g/2005#other":           "other", 			
		"http://schemas.google.com/g/2005#other_fax":       "other_fax", 		
		"http://schemas.google.com/g/2005#pager":           "pager", 			
		"http://schemas.google.com/g/2005#radio":           "radio", 			
		"http://schemas.google.com/g/2005#telex":           "telex", 			
		"http://schemas.google.com/g/2005#tty_tdd":         "tty_tdd", 		
		"http://schemas.google.com/g/2005#work":            "work", 			
		"http://schemas.google.com/g/2005#work_fax":        "work_fax", 		
		"http://schemas.google.com/g/2005#work_mobile":     "work_mobile", 	
		"http://schemas.google.com/g/2005#work_pager":      "work_pager"
	};
	
	if (info.substring(0,4)=='http'){
		if (info in types)
			return types[info];
		else
			return 'home';
	}
	else{
		for(var key in types){
		  if (types[key]==info)
			 return key;
		}
		return "http://schemas.google.com/g/2005#home";
	}
}

/*
  ex:
    startTime = {year: 2010, month:11, date: 13, hour: 3, minute: 45, second: 10}
	interval = {hour: 3, minute: 45, second: 10}
	
	return:
	
*/
function getEndTime(startTime, contactEntry)
{
  	var duration;
	var ufields=contactEntry.getUserDefinedFields();
	for(var i=0;i<ufields.length;i++){
		var ufield=ufields[i];
		if (ufield.key=='duration'){
			duration=ufield.getValue();
			break;
		}

	}
	if (!duration) duration='45';		
	var interval = getAsTime(duration);
  
	var hour = parseInt(interval.hour)   + startTime.hour;
	var mins  = parseInt(interval.minute) + startTime.minute;
	var secs  = parseInt(interval.second) + startTime.second;

	if (secs>=60) { secs = -(60 - secs); mins = parseInt(mins)+1; }
	if (mins>=60) { mins = -(60 - mins); hour = parseInt(hour)+1; }
	if (hour>=24) { hour = -(24 - hour); }

	return {
		year:		startTime.year,
		month: 		startTime.month,
		date: 		startTime.date,
		hour: 		hour,
		minute: 	mins,
		second: 	secs
	};
}

function getGadgetURL(){
	var url = (window.document.location.search ? window.document.location.search : '');
	if (url.length>0){
		url = url.replace(/\?url\=/ig,'');
		var asArray= url.split('xml');
		if (asArray.length>0)
			url = asArray[0]+'.xml';
	};
	return url;
};


function properCase(s){return s.toLowerCase().replace(/^(.)|\s(.)/g,function($1){return $1.toUpperCase();});}

function setScope(service){
	var scope;
	if (service=='calendar')
		scope = "http://www.google.com/calendar/feeds";
	else if (service=='contacts')
		scope = "http://www.google.com/m8/feeds";
	return google.accounts.user.checkLogin(scope);
};


function filterContacts(chrs,callback){
	var items = [];
	var entry = null;
	var pattern = new RegExp('\\b'+chrs,"i");
	for (var i = 0; i<contactEntries.length; i++) {
		entry = contactEntries[i];
		var id = entry.id.$t;
		var name = entry.title.$t;
		if (name.search(pattern)>=0){
			name = properCase(name);
			var autosugestItem = {
				'id'    : id,
				'info'  : '',
				'value' : name,
				'seq'   : i
			};
			items.push(autosugestItem);					
		}
	}
	items.sort(function(a,b){
		return (a.value==b.value)?0:(a.value>b.value?1:-1);
	});
	var response={
		status:'OK',
		data: {
			results: items
		}
	};
	callback(response);
};

function setupInputSearch(){
	var inputId = 'contactsearch';
	var target = $('#'+inputId);
	if(!target)
		return;	
	var autoSuggest = new AutoSuggest(
		inputId,
		{
			varname:"input",
			json:true,
			noresults: "New",
			//noresultslink: "http://www.google.com/contacts/c/u/0/ui/ContactManager?titleBar=false",
            noresultslink: function(ev){
                var supported_views = gadgets.views.getSupportedViews();
                gadgets.views.requestNavigateTo(supported_views['canvas']);               
            },
			searchFunction: function(typedstr,callback){					
				filterContacts(typedstr,callback);
			},
			callback: function (obj, typedstr) { 
				var text = $.trim(obj.value);
				if (text.length>=3){              
					setCurrentContact(contactEntries[obj.seq]);
				}
			}
		}
	); 
};


function showOneSection(toshow) {
  var sections = [ 'search', 'approval', 'waiting' ];
  for (var i=0; i < sections.length; ++i) {
	var s = sections[i];
	var el = document.getElementById(s);
	if (s === toshow) {
	  el.style.display = "block";
	} else {
	  el.style.display = "none";
	}
  }
}

// Process returned JSON feed to display data.
function showResults(result) {
	showOneSection('search');
	//list = result.feed.entry;
	//setupInputSearch(list);
	setupInputSearch();
}

function msg(txt,tm){
	$('.mmlib_table').hide();
	if (txt && txt.length>0){
        var minimsg = new gadgets.MiniMessage(selfModuleId,document.getElementById("messages"));
        if ((!tm)||(tm===0)){
            minimsg.createDismissibleMessage(txt);
        }
        else{
            minimsg.createTimerMessage(txt,tm);
        }
    }
};

function resetLastEntry(){
	$('#contactsearch').data('entry',null);
	$('#TabEventSave').data('event',null);
	$('#contactsearch').val('');
	$('#divtab').hide();
	$('#options').hide();
	$('#divcancel').hide();
	$('#divevent').hide();
	$('.tablib_main_container').hide();
	$('.fieldinp').val('');
	$('.bigtext').val('');
    $('#divcancelreason').html("");
    $('#cancelreasondetail').hide();
	$('#contactsearch').focus();
};


function saveEventDetails(){
	var event=$('#TabEventSave').data('event');
	if (event){
		// Remove previous 
		var properties = event.getExtendedProperties();
		if (properties && properties.length>0){
			for(var j=properties.length-1;j>=0;j--){
				if (properties[j].getName()==='cancelreason'){
					properties.splice(j,1);
				}
				else if (properties[j].getName()==='price'){
					properties.splice(j,1);
				}
			}
		}
		// Collect form data
		var eventpriceref       = $('#price').val();
		var cancelreasonref     = $('input:checked[name="cancelreason"]').val();
		var cancelreasondetail  = $('#cancelreasondetail').val();
		
		var prop;
		if (cancelreasonref && cancelreasonref.length>0){			
			prop = new google.gdata.ExtendedProperty();
			prop.setName('cancelreason');
			prop.setValue(cancelreasonref);
			properties.push(prop);
			
			var text = event.getContent().getText();
			text = ('\nCanceled in <b>'+(new Date()).toUTCString() + '</b>\nReason: <b>'+cancelreasonref+'</b>\n')+$.trim(cancelreasondetail)+'\n---\n'+text;
			event.content.setText(text);		
		}
		
		if (eventpriceref && eventpriceref.length>0){
			prop = new google.gdata.ExtendedProperty();
			prop.setName('price');
			prop.setValue(eventpriceref);
			properties.push(prop);
		}

		// Before update the event move to the date
		var dt;
		if (event.gd$recurrence && event.gd$recurrence.$t.length>0){			
			var items = event.gd$recurrence.$t.split('\n');
			for (var i=0;i<items.length;i++){
				if (items[i].substring(0,7)==='DTSTART'){
					var rowstr = items[i].split(':')[1]; // 20101225T235945
					dt = new Date(rowstr.substring(0,4),rowstr.substring(4,2),rowstr.substring(6,2));
					break;
				}
			}
		}
		else{
			var dt = new Date(event.gd$when[0].startTime);
		}
		if (dt){
			google.calendar.showDate(dt.getFullYear(), dt.getMonth()+1, dt.getDate() );
		}
		event.updateEntry(
			function(ret){
				console.log(ret.entry['gd$etag']);
				resetLastEntry();
				msg('Updated',2);
			},
			function(ret){
				resetLastEntry();
				msg('Error');
				console.log(ret.toString());
			},
			{'etag':event['gd$etag']}
		);

	}
}

function saveEvent(event){
	msg('Updating',2);
	var contactId=event['gd$where'][0]['valueString'];
	event['gd$where'][0]['valueString']=event.getSelfLink().href;
	
	// Remove any existing extended properties
	var properties = event.getExtendedProperties();
	if (properties && properties.length>0){
		for(var j=properties.length-1;j>=0;j--){
			if (properties[j].getName()==='contactid'){
				properties.splice(j,1);
			}
			else if (properties[j].getName()==='price'){
				properties.splice(j,1);
			}
		}
	}
	
	
	var prop = null;
	// Add the contact Id
	prop=new google.gdata.ExtendedProperty();
	prop.setName('contactid');
	prop.setValue(contactId);
	properties.push(prop);	

	// Add the price
	var contactEntry = getContactById(contactId);
	if (contactEntry){
		var price;
		var duration;
		var ufields=contactEntry.getUserDefinedFields();
		for(var i=0;i<ufields.length;i++){
			var ufield=ufields[i];
			if (ufield.key=='price')
				price=ufield.getValue();
			else if (ufield.key=='duration')
				duration=ufield.getValue();
		}
		if (price){
			prop = new google.gdata.ExtendedProperty();
			prop.setName('price');
			prop.setValue(price);
			properties.push(prop);	
		}
	}

	//--- Set the extended properties
	event.setExtendedProperties(properties);	
	event.updateEntry(
		function(ret){
			console.log(ret.entry['gd$etag']);
			resetLastEntry();
			msg('Updated',2);
		},
		function(ret){
			resetLastEntry();
			msg('Error');
			$('#revoke').show();
			console.log(ret.toString());
		},
		{'etag':event['gd$etag']}
	);
};

function onDataReady(){
	if (calendar && contacts && contactEntries && contactEntries.length>0){
		msg('Checking',2);
		var url = "https://www.google.com/calendar/feeds/default/private/full";
		var query = new google.gdata.calendar.CalendarEventQuery(url);
		query.setMaxResults(3); // Update last three events...
		query.setOrderBy('lastmodified');
		query.setSortOrder('descending');
		var onSuccess = function(result){
			try{
				if (!(result.feed.entry && result.feed.entry.length>0))
					return;
				for(var i=0;i<result.feed.entry.length;i++){
					var event=result.feed.entry[i];
					if (event['gd$where'] && event['gd$where'].length>0){
						var where=event['gd$where'][0]['valueString'];						
						if (where.search(/calendar/i)>0)
							return; // so contactid has already been replaced by calendar
						saveEvent(event);
					}
				}
			}
			catch(e){
				resetLastEntry();
				msg('Unknown Error');
			};
		};
		var onError = function(err){
			try{
				console.log(err.toString());
				google.accounts.user.logout(function(){
					msg('Error');
					showOneSection('approval');
					resetLastEntry();
				});	
			}
			catch(e){
				resetLastEntry();
				msg('Unknown Error');			
			}
		};
		calendar.getEventsFeed(query, onSuccess, onError);
	}		
};

function saveContact(contactEntry){
	msg('Saving',5);
	contactEntry = updateContact(contactEntry);
	// Save it
	contactEntry.updateEntry(
		function(ret){
			msg('Saved',2);
		},
		function(ret){
			msg('Error');
			console.log(ret.toString());
		},
		{'etag':'*'}
	);
};

function updateContact(contactEntry){

	// Title
	var title = $.trim($('#contactsearch').val());
	if (title.length>0){
		contactEntry.title.text=title;
		contactEntry.title.type='text';
	}
	// Group
	var groupref=$.trim($('#group').val());
	if ((groupref.length>0) && (groupref.substring(0,4)=='http'))
		contactEntry['gContact$groupMembershipInfo'][0]['href']=groupref;
	
	// Phones
	phones = [];	
	$('input[name="phone"]').each(function(i){
		var phonenumber = $.trim($(this).val());
		if (phonenumber.length>0){
			var phonelabel = $(this).next().text();
			var phonetype = getPhoneType(phonelabel);
			// object
			var phone = new google.gdata.PhoneNumber();
			phone['rel']=phonetype;
			phone['$t']=phonenumber;
			phones.push(phone);
		}
	});
	contactEntry.setPhoneNumbers(phones);
	
	var ufields = [];	
	//Price
	var priceref = $.trim($('#price').val());
	if (priceref.length>0){
		var price = new google.gdata.contacts.UserDefinedField();
		price.key='price';
		price.setValue(priceref);
		ufields.push(price);
	}
	
	//duration
	var durationref = $('input:checked[name="duration"]').val();
	if (durationref.length>0){
		var duration = new google.gdata.contacts.UserDefinedField();
		duration.key='duration';
		duration.setValue(durationref);
		ufields.push(duration);
	}
	
	contactEntry.setUserDefinedFields(ufields);
	return contactEntry;

};

function setCurrentContact(contactEntry){
	$('#contactsearch').data('entry',contactEntry);
	$('#contactsearch').val(contactEntry.getTitle().getText());
	//-----------------------------------------------------
	var contactGroupId=contactEntry['gContact$groupMembershipInfo'][0]['href'];
	$('#group').val(contactGroupId);
	//-----------------------------------------------------
	var phones = '';
	if (contactEntry['gd$phoneNumber']){
		for(var iphone=0;iphone<contactEntry['gd$phoneNumber'].length;iphone++){
			var phonetype = contactEntry['gd$phoneNumber'][iphone]['rel'];
			var phonenumber = contactEntry['gd$phoneNumber'][iphone]['$t'];
			if ($.trim(phonenumber)!==''){
				phonenumber=phonenumber.replace(/\"/g,'');
				phones=phones+'<div class="subrow"><input name="phone" type="text" value="'+phonenumber+'" class="fieldinp fieldphone"><span class="rlabel">'+getPhoneType(phonetype)+'</span></div>';
			}
		}
		$('#phones').html(phones);
	}
	//-----------------------------------------------------
	var price;
	var duration;
	var ufields=contactEntry.getUserDefinedFields();
	for(var i=0;i<ufields.length;i++){
		var ufield=ufields[i];
		if (ufield.key=='price')
			price=ufield.getValue();
		else if (ufield.key=='duration')
			duration=ufield.getValue();
	}
	
	if (price) $('#price').val(price);
	if (!duration) duration='45';
	
	var durationhtml='';
	var checked = '';
	for (var i=0;i<durations.length;i++){
		checked = (durations[i]==parseInt(duration)) ? 'checked': '';
		durationhtml=durationhtml+'<span class="lblradio">'+durations[i]+'</span><input name="duration" type="radio" value="'+durations[i]+'" '+checked+' class="inpradio">';
	}
	$('#divduration').html(durationhtml);
		
	// show divs...
	showeventdiv('details');
	$('#divtab').show();
	$('.tablib_main_container').show();
	$('#options').show();				
};

function displayEventDetails(eventEntry){
	var properties = eventEntry.getExtendedProperties();
	var cancelreason;
	var contactSelfLink;
	var price;
	if (properties && properties.length>0){
		for(var j=0;j<properties.length;j++){
			if ((!contactSelfLink) && (properties[j].getName()==='contactid')){
				contactSelfLink=properties[j].getValue();
			}
			else if ((!cancelreason) && (properties[j].getName()==='cancelreason')){
				cancelreason=properties[j].getValue();
			}
			else if ((!price) && (properties[j].getName()==='price')){
				price=properties[j].getValue();
			}
		}
	};
	if (contactSelfLink){
		for(var i=0;i<contactEntries.length;i++){
			if (contactEntries[i].getSelfLink().href==contactSelfLink){
				setCurrentContact(contactEntries[i]);
				var html='';
				var checked = '';
				for (var i=0;i<cancelreasons.length;i++){
					if (cancelreason){
						checked = (cancelreasons[i]==cancelreason) ? 'checked': '';
					}
					html=html+'<div class="subrow">';
					html=html+'<input id="cancelreason" name="cancelreason" type="radio" value="'+cancelreasons[i]+'" '+checked+'>';
					html=html+'<span class="rlabel" onclick="onRLabelClicked(this);">'+cancelreasons[i]+'</span>';
					html=html+'</div>';
				}
				$('#TabEventSave').data('event',eventEntry);
				$('#divcancelreason').html(html);
                $('#cancelreasondetail').show();
                $('#diveventmenu').html('&gt; Cancel');
				$('#price').val(price);
				//$('#price')..attr('disabled', 'disabled');
				break;
			}
		}
	}
    else{
        $('#diveventmenu').html('');
    }
};

function loadEvent(id){
	var onSuccess=function(response){
		displayEventDetails(response.entry);
	};
	var onError=function(response){
		msg("");
		console.log("Load Event Error");
	};
	calendar.getCalendarEventEntry(id,onSuccess,onError);
};

function getCalendarById(id){
	for(var i=0;i<calendarEntries.length;i++){
		if(calendarEntries[i].id.$t==id)
			return calendarEntries[i];
	}
	return null;
};

function getContactById(id){
	for(var i=0;i<contactEntries.length;i++){
		if(contactEntries[i].getSelfLink().href==id)
			return contactEntries[i];
	}
	return null;
};

function onNewEvent(event) {
	if (event && calendar && contacts && contactEntries && contactEntries.length>0){
		if ('id' in event){
			var eventSelfhRef = event['location'];
			if (eventSelfhRef && eventSelfhRef.length>0){
				tabs.setSelectedTab(0);
				msg('wait',2);
				google.calendar.showEvent(event['id']);
				loadEvent(eventSelfhRef);
			}
		}
		else{
			$('#TabEventSave').data('event',null);
			var contactEntry = $('#contactsearch').data('entry');
			if (contactEntry){
				tabs.setSelectedTab(0);
				contactEntry=updateContact(contactEntry);			
				event['endTime']=getEndTime(event.startTime, contactEntry);
				event['title']=contactEntry.getTitle().getText();
				event['location']=contactEntry.getSelfLink().href;
				//google.calendar.composeEvent(event);
				msg('Editing Event',4);
			}
		}
	}
	else{
		$('#contactinfo').html('');
	}
};

function fetchCalendars(){
	msg('Loading calendars...',2);
	var feedURI='http://www.google.com/calendar/feeds/default/allcalendars/full';
	var oAuthManager = function(response){
		if (response.oauthApprovalUrl){
			var popup = shindig.oauth.popup({
				destination: response.oauthApprovalUrl,
				windowOptions: null,
				onOpen: function() { showOneSection('waiting'); },
				onClose: function() { fetchCalendars(); }
			});          
			var personalize = document.getElementById('personalize');
			personalize.onclick = popup.createOpenerOnClick();
			var approvaldone = document.getElementById('approvaldone');
			approvaldone.onclick = popup.createApprovedOnClick();
			showOneSection('approval');
		} 
		else if (response.feed){
			calendarEntries = [];
			for(var i=0;i<response.feed.entry.length;i++){
				var entry = response.feed.entry[i];
				var acl = (entry.gCal$accesslevel && entry.gCal$accesslevel.value)?entry.gCal$accesslevel.value:'owner';
				if (acl=='owner'||acl=='root'||acl=='editor'){
					calendarEntries.push(entry);
				}
			};
			fetchGroups();
		} 
		else {
			var err='';
			if (response.oauthError)
				err='OAuth error: ' + response.oauthError + ': ' + response.oauthErrorText;
			else if (response.message)
				err=response.message
			else
				err='unknown error'
			console.log(err);
			showOneSection('approval');
			msg(err);
		}			
	};
	calendar.getEventsFeed(feedURI, oAuthManager, oAuthManager);
};

function fetchGroups(){
	msg('Loading Contact groups...',2);
	var feedUri = "http://www.google.com/m8/feeds/groups/default/full";	
	var oAuthManager = function(response){
		if (response.oauthApprovalUrl){
			var popup = shindig.oauth.popup({
				destination: response.oauthApprovalUrl,
				windowOptions: null,
				onOpen: function() { showOneSection('waiting'); },
				onClose: function() { fetchGroups(); }
			});          
			var personalize = document.getElementById('personalize');
			personalize.onclick = popup.createOpenerOnClick();
			var approvaldone = document.getElementById('approvaldone');
			approvaldone.onclick = popup.createApprovedOnClick();
			showOneSection('approval');
		} 
		else if (response.feed){
			$('#group').html('');
			groupEntries=[];
			contactEntries=[];
			for(var i=0;i<response.feed.entry.length;i++){
				if (!response.feed.entry[i]['gContact$systemGroup']){
					groupEntries.push(response.feed.entry[i]);
				}
			}
			for(var j=0;j<groupEntries.length;j++){
				$('#group').append('<option value="'+groupEntries[j].id.$t+'">'+groupEntries[j].title.$t+'</option>');
				if (j==groupEntries.length-1){
					fetchContacts(groupEntries[j],function(sts){
						if (sts=='ok'){
							setupInputSearch();
							showOneSection('search');
							msg('Ready!',2);
							resetLastEntry();
						}
						else{
							showOneSection('approval');
							msg(sts);		
						}
					});
				}
				else{
					fetchContacts(groupEntries[j]);
				}
			}				
		} 
		else {
			var err='';
			if (response.oauthError)
				err='OAuth error: ' + response.oauthError + ': ' + response.oauthErrorText;
			else if (response.message)
				err=response.message
			else
				err='unknown error'
			console.log(err);
			showOneSection('approval');
			msg(err);
		}			
	};
	var query = new google.gdata.contacts.ContactQuery(feedUri);		
	query.setMaxResults(100);
	contacts.getContactGroupFeed(query, oAuthManager, oAuthManager);		
}

function fetchContacts(group,onFinish){	
	msg(group.title.$t,2);
	var feedUri = 'http://www.google.com/m8/feeds/contacts/default/full';	
	var oAuthManager = function(response){
		if (response.oauthApprovalUrl){
			var popup = shindig.oauth.popup({
				destination: response.oauthApprovalUrl,
				windowOptions: null,
				onOpen: function() { showOneSection('waiting'); },
				onClose: function() { fetchContacts(); }
			});          
			var personalize = document.getElementById('personalize');
			personalize.onclick = popup.createOpenerOnClick();
			var approvaldone = document.getElementById('approvaldone');
			approvaldone.onclick = popup.createApprovedOnClick();
			showOneSection('approval');
		} 
		else if (response.feed){
			contactEntries=contactEntries.concat(response.feed.entry);
			if (onFinish && (typeof onFinish)=='function'){
				onFinish('ok');
			}
		} 
		else {			
			var err='';
			if (response.oauthError)
				err='OAuth error: ' + response.oauthError + ': ' + response.oauthErrorText;
			else if (response.message)
				err=response.message
			else
				err='unknown error'
			console.log(err);
			if (onFinish && (typeof onFinish)=='function'){
				onFinish(err);
			}
		}			
	};		
	
	var query = new google.gdata.contacts.ContactQuery(feedUri);		
	query.setMaxResults(400);
	//query.setOrderBy('title');
	//query.setSortOrder('ascending');	
	query.setGroup(group.id.$t);
	contacts.getContactFeed(query, oAuthManager, oAuthManager);
};	

function initServices(){
	if (contacts==null){
		contacts = new google.gdata.contacts.ContactsService('ContactSearch');
		contacts.useOAuth('google');
	}
	if (calendar==null){
		calendar = new google.gdata.calendar.CalendarService('CalendarSearch');
		calendar.useOAuth('google');
		fetchCalendars();
	};
};

function onRLabelClicked(e){
	if (e && e.parentNode && e.parentNode.children && e.parentNode.children[0]){
		var isChecked = e.parentNode.children[0].checked;
		e.parentNode.children[0].checked = (!isChecked);
	}
};

function goToRevokePage()
{
	calendar = null;
	contacts = null;
	calendarEntries = null;
	groupEntries = null;
	contactEntries = null;
	var supported_views = gadgets.views.getSupportedViews();
	gadgets.views.requestNavigateTo(supported_views['canvas']);
    showOneSection('approval');
};

function showeventdiv(id)
{
	if (id=='details'){
		$('#diveventmenu').html('&gt; Cancel');
		$('#cancel').hide();
		$('#details').show();		
	}
	else if (id=='cancel'){
		$('#diveventmenu').html('&gt; Details');
		$('#details').hide();
		$('#cancel').show();		
	}
	else{
		$('#diveventmenu').html('');
		$('#details').hide();
		$('#cancel').hide();
	}
};

function init(){

	msg('Loading...',5);
	google.calendar.subscribeToDataChange(onDataReady);
	google.calendar.read.subscribeToEvents(onNewEvent);		
	
	tabs = new gadgets.TabSet(selfModuleId, "Contact");
	
	tabs.addTab("Contact", {contentContainer: document.getElementById("tabContact"), index:0});
	tabs.addTab("Event", {contentContainer: document.getElementById("tabEvent"), index:1});
	tabs.addTab("Docs", {contentContainer: document.getElementById("tabDocs"), index:2});
		
	$('#gadgeturltext').html(getGadgetURL());
	$('#revokelink').click(goToRevokePage);
	
	$('.tablib_main_container').hide();
	
	$('#contactclear').click(function(e){
		resetLastEntry();
	});
	
	$('#TabSearchSave').click(function(e){
		var contactEntry = $('#contactsearch').data('entry');
		if (contactEntry)
			saveContact(contactEntry);
	});

	$('#TabEventSave').click(function(e){
		saveEventDetails();
	});
	
	$('#TabSearchReset').click(function(e){
		var event=$('#TabEventSave').data('event');
		if (event){
			var dt = new Date(event.gd$when[0].startTime);
			google.calendar.showDate(dt.getFullYear(), dt.getMonth()+1, dt.getDate() );			
		}
		resetLastEntry();
	});
	
	$('#TabEventReset').click(function(e){
		resetLastEntry();
	});
	
	showeventdiv('details');
	
	$('#diveventmenu').click(function(){
		if ($('#cancel').is(':visible')){
			showeventdiv('details');
		}
		else{
			showeventdiv('cancel');
		}
	});
	
	
	google.setOnLoadCallback(function(){
		//showOneSection('approval'); // debug purposes
		//$('#reload').show().click(initServices); // debug purposes
		setTimeout( initServices, 2 );;
	});

};


